#pragma once
#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/stat.h>
#include<cerrno>
#include<cstdio>
#include<unistd.h>
#include<fcntl.h>
#define Default -1
#define Creator 1
#define User 2
#define Read  O_RDONLY
#define Write O_WRONLY
#define SIZE 1024
const std::string pathname = "./myfifo";

class NamePiped
{
private: 
    bool OpenPipedFile(int mode)
    {
        _fd = open(pathname.c_str(),mode);
        if(_fd < 0) return false;
        return true;
    }
public:
    // 创建命名管道文件
    NamePiped(const std::string &filename, int who)
        : _filename(filename), _id(who),_fd(Default)
    {
        if (_id == Creator)
        {
            std::cout << "检测到您是Creator,正在创建对应管道" << std::endl;
            int res = mkfifo(_filename.c_str(), 0666);
            if (res < 0)
            {
                perror("mkfifo");
            }
        }
    }
    bool OpenForRead()
    {
        return OpenPipedFile(Read);
    }
    bool OpenForWrite()
    {
        return OpenPipedFile(Write);
    }
    int ReadPipeData(std::string* message)
    {
        char buf[SIZE];
        ssize_t n = read(_fd,buf,sizeof buf);
        if(n > 0)
        {
            buf[n] = '\0';
            *message = buf;
        }
        return n;
    }
    int WritePipeData(const std::string& message)
    {
        ssize_t n = write(_fd,message.c_str(),message.size());
        return n;
    }
    // 删除命名管道文件
    ~NamePiped()
    {
        if (_id == User)
        {
            std::cout<<"检测到User,正在删除命名管道"<<std::endl;
            int res = unlink(_filename.c_str());
            if (res < 0)
            {
                perror("unlink");
            }
        }
        if(Default != _fd)
        {
            //关闭文件fd
            close(_fd);
        }
    }

private:
    const std::string _filename;
    int _id;
    int _fd;
};
